package io.noties.markwon.base.image


import android.widget.TextView
import android.text.Spanned
import io.noties.markwon.base.*
import io.noties.markwon.base.image.load.AsyncDrawableOrderLazyScheduler
import io.noties.markwon.base.image.load.AsyncRecycleDrawableLoader
import io.noties.markwon.base.image.load.ExtGlideStore
import io.noties.markwon.base.image.load.GlideAsyncRecycleDrawableLoader
import io.noties.markwon.base.image.span.RecycleImageSpanFactory
import org.commonmark.node.Image


class GlideImagesWithGifPlugin  constructor(glideStore: ExtGlideStore) : AbstractMarkwonPlugin() {

    private val glideAsyncRecycleDrawableLoader:AsyncRecycleDrawableLoader = GlideAsyncRecycleDrawableLoader(glideStore)

    override fun configureSpansFactory(builder: MarkwonSpansFactory.Builder) {
        builder.setFactory(Image::class.java, RecycleImageSpanFactory())
    }

    override fun configureConfiguration(builder: MarkwonConfiguration.Builder) {
        builder.asyncDrawableLoader(glideAsyncRecycleDrawableLoader)
    }

    override fun beforeSetText(textView: TextView, markdown: Spanned) {
        AsyncDrawableOrderLazyScheduler.unscheduled(textView)
    }

    override fun afterSetText(textView: TextView) {
        AsyncDrawableOrderLazyScheduler.schedule(textView)
        //this.glideAsyncRecycleDrawableLoader.glideStore.clearMemoryCache();
    }

    companion object {
        fun create(glideStore: ExtGlideStore): GlideImagesWithGifPlugin {
            return GlideImagesWithGifPlugin(glideStore)
        }
    }
}